<?php


namespace App\Http\Requests\ApiV2;


use App\Services\Business\Models\WishFragment;
use App\Services\Business\Models\Wish;
use Illuminate\Support\Facades\Auth;

class WishFragmentRequest extends BaseRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'required|max:120',

        ];
    }

    public function messages()
    {
        return [
            'title.required' => __('请输入标题'),
            'title.max' => __('动态长度不能超过:size个字符', ['size' => 120]),

        ];
    }

    public function filldata()
    {
        $wishId = (int)$this->input('wish_id');
        $userId = Auth::id();
        $points = $this->input('points');
        $point = array_sum(array_column($points, 'value'));


        //取最新一条的记录
        $fragment = WishFragment::query()
            ->where('wish_id', $wishId)
            ->when($this->method() == 'PUT', function ($query) use ($wishId) {
                return $query->where('id', '<', $this->route('id'));
            })
            ->latest()->first();
        //如果是更新 取当前
        $currentFragment = [];
        if ($this->method=='PUT') {
            $currentFragment = WishFragment::query()->where('id',$this->route('id'))->first();
        }

        return [
            'user_id' => $userId,
            'title' => (string)$this->input('title'),
            'wish_id' => $wishId,
            'images' => (array)$this->input('images', []),
            'video_ids' => (array)$this->input('video_ids', []),
            'point' => $point,
            'wish_reward' => $this->input('points'),
            'total_point' => $fragment ? $fragment->total_point + $point : $point,
            'difference'=>($this->method() == 'PUT')? $point - $currentFragment->point :0,
        ];
    }
}
